<template>
	<view class="nc-payment-content">
		<view class="payment-amount">
			<text class="amount-tit">支付金额</text>
			<view class="amount-num">
				￥
				<text>{{ payInfo.pay_money }}</text>
			</view>
			<view class="amount-desc">
				<text>{{ payInfo.pay_body }}</text>
			</view>
		</view>

		<view class="payment-balance" v-if="balance > 0 && payInfo.type != 4">
			<text class="balance-tit">余额抵扣：</text>
			<text class="balance-num">￥{{ balance }}</text>
			<switch style="transform:scale(0.7)" @change="useBalance" checked="true" />
		</view>

		<view class="payment-style" v-if="payTypeList.length">
			<text class="style-tit">请选择支付方式</text>
			<view class="style" v-for="(item, index) in payTypeList" :key="index" @click="selectPayType(index)">
				<view class="pic iconfont" :class="item.icon"></view>
				<text>{{ item.name }}</text>
			    <radio style="transform:scale(0.9)" :checked="index == payType" v-if="payInfo.pay_money != 0"/>
				<radio style="transform:scale(0.9)" v-else/>
			</view>
		</view>
		<button type="primary" class="payment-btn" :class="isIphoneX ? 'payment-bottom' : ''" @click="pay">确认支付</button>
		<web-view :src="payUrl" v-if="payUrl != ''"></web-view>

		<loading-cover ref="loadingCover"></loading-cover>
		<ns-login ref="login" href="pay"></ns-login>
	</view>
</template>

<script>
import http from 'common/js/http.js';
import { Weixin } from 'common/js/wx-jssdk.js';
import loadingCover from '@/components/loading/loading.vue';
import nsLogin from 'components/ns-login/ns-login.vue';

export default {
	components: {
		loadingCover,
		nsLogin
	},
	data() {
		return {
			outTradeNo: '',
			payInfo: {},
			payType: 0,
			payTypeList: [],
			isUseBalance: true,
			balance: 0,
			payUrl: [],
			flag: false, //防重复标识
			isIphoneX: false, //判断手机是否是iphoneX以上
			payMoney: 0
		};
	},
	onBackPress(options) {
		var pages = getCurrentPages();
		var page = pages[pages.length - 2];
		if (page.route.indexOf('pages/member/recharge/recharge') == -1) {
			this.$util.redirectTo('/pages/order/list/list', { status: 0 });
			return true;
		}
	},
	onLoad(option) {
		if (option.out_trade_no) this.outTradeNo = option.out_trade_no;
		uni.getSystemInfo({
			success: res => {
				if (res.model.search('iPhone X') != -1) {
					this.isIphoneX = true;
				}
			}
		});
	},
	onHide() {
		this.flag = false;
	},
	methods: {
		getPayInfo() {
			this.sendRequest({
				url: 'System.Pay.payInfo',
				data: { out_trade_no: this.outTradeNo },
				success: res => {
					if (res.data) {
						this.payInfo = res.data;
						this.payInfo.pay_money = parseFloat(this.payInfo.pay_money).toFixed(2);
						this.payMoney = this.payInfo.pay_money;
						if (this.$refs.loadingCover == undefined) return;
						this.$refs.loadingCover.hide();
					} else {
						this.$util.showToast({
							title: '未获取到支付信息',
							success: () => {
								setTimeout(() => {
									this.$util.redirectTo('/pages/index/index/index', {}, 'tabbar');
								}, 1000);
							}
						});
					}
				}
			});
		},
		getPayType() {
			this.payTypeList = [];
			// 仅在h5编译
			// #ifdef H5
			this.sendRequest({
				url: 'System.Pay.getPayConfig',
				success: res => {
					if (res.code == 0) {
						let payType = res.data;
						payType.forEach(item => {
							if (item.addon_name == 'NsAlipay' && item.is_use) {
								this.payTypeList.push({
									name: '支付宝支付',
									provider: 'NsAlipay',
									icon: 'iconzhifubaozhifu-'
								});
							}
							if (item.addon_name == 'NsWeixinpay' && item.is_use) {
								this.payTypeList.push({
									name: '微信支付',
									provider: 'NsWeixinpay',
									icon: 'iconweixinzhifu'
								});
							}
						});
					}
				}
			});
			// #endif

			// 仅在小程序编译
			// #ifdef MP
			uni.getProvider({
				service: 'payment',
				success: res => {
					if (res.errMsg == 'getProvider:ok' && res.provider) {
						res.provider.forEach(item => {
							switch (item) {
								case 'alipay':
									this.payTypeList.push({
										name: '支付宝支付',
										provider: 'alipay',
										icon: 'iconzhifubaozhifu-'
									});
									break;
								case 'wxpay':
									this.payTypeList.push({
										name: '微信支付',
										provider: 'wxpay',
										icon: 'iconweixinzhifu'
									});
									break;
							}
						});
					}
				}
			});
			// #endif
		},
		pay() {
			if (this.flag) return;
			this.flag = true;

			// #ifdef H5
			this.h5Pay();
			// #endif
			// #ifdef MP-WEIXIN
			this.mpPay();
			// #endif
		},
		/**
		 * h5支付
		 */
		async h5Pay() {
			// 如果要使用余额
			if (this.isUseBalance && this.payInfo.type != 4) {
				var isNext = await this.bindBalance();
				if (!isNext) return;
			}
			this.sendRequest({
				url: 'System.Pay.onlinePay',
				data: {
					out_trade_no: this.outTradeNo,
					type: this.payTypeList[this.payType].provider,
					is_uniapp: 1
				},
				success: res => {
					if (res.code == 0) {
						let data = res.data.data;
						if (res.data.code >= 0) {
							// 如果是微信浏览器
							if (this.payTypeList[this.payType].provider == 'NsWeixinpay' && this.$util.isWeiXin()) {
								if (data.return_type == 'data') {
									this.sendRequest({
										url: 'System.WchatPublic.getJsApiConfig',
										data : {
											url: window.location.href
										},
										success: jsApiRes => {
											if (jsApiRes.code == 0) {
												var wxJS = new Weixin();
												wxJS.init(jsApiRes.data);
												wxJS.pay(JSON.parse(data.data), res => {
													if (res.errMsg == 'chooseWXPay:ok') {
														this.$util.redirectTo('/pages/pay/callback_pay/callback_pay', { out_trade_no: this.outTradeNo }, '', 'redirectTo');
													} else {
														this.$util.showToast({
															title: res.errMsg,
															success: () => {
																setTimeout(() => {
																	this.$util.redirectTo(
																		'/pages/pay/callback_pay/callback_pay',
																		{ out_trade_no: this.outTradeNo },
																		'',
																		'redirectTo'
																	);
																}, 1500);
															}
														});
													}
												});
											} else {
												this.$util.showToast({ title: jsApiRes.message });
											}
										}
									});
								}
							} else {
								if (data.return_type == 'html') {
									const httpString = function(s) {
										var reg = /(https?|http|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/g;
										s = s.match(reg);
										return s;
									};
									let urlArr = httpString(data.html);
									if (urlArr[0] != undefined) this.payUrl = urlArr[0];
								} else if (data.return_type == 'url') {
									this.payUrl = data.url;
								}
							}
						} else {
							this.$util.showToast({ title: data.out_message });
							this.flag = false;
						}
					} else {
						this.$util.showToast({ title: res.message });
						this.flag = false;
					}
				}
			});
		},
		/**
		 * 小程序支付
		 */
		async mpPay() {
			// 如果要使用余额
			if (this.isUseBalance && this.payInfo.type != 4) {
				var isNext = await this.bindBalance();
				if (!isNext) return;
			}
			if (this.payTypeList[this.payType].provider == 'wxpay') {
				this.sendRequest({
					url: 'System.Pay.appletWechatPay',
					data: {
						out_trade_no: this.outTradeNo,
						provider: this.payTypeList[this.payType].provider
					},
					success: res => {
						if (res.data.result_code == 'SUCCESS' && res.data.return_code == 'SUCCESS') {
							uni.requestPayment({
								provider: this.payTypeList[this.payType].provider,
								timeStamp: JSON.stringify(res.data.timestamp),
								nonceStr: res.data.nonce_str,
								package: 'prepay_id=' + res.data.prepay_id,
								signType: 'MD5',
								paySign: res.data.PaySign,
								success: res => {
									this.$util.redirectTo('/pages/pay/callback_pay/callback_pay', { out_trade_no: this.outTradeNo }, '', 'redirectTo');
								},
								fail: res => {
									this.flag = false;
									if (res.errMsg == 'requestPayment:fail cancel') {										
										this.$util.showToast({ title: '您已取消支付' });										
									} else {
										uni.showModal({ content: '支付失败,失败原因: ' + res.errMsg, showCancel: false });
									}
									this.$util.redirectTo('/pages/order/list/list');
								}
							});
						} else {
							this.$util.showToast({ title: res.data.return_msg });
							this.flag = false;
						}
					}
				});
			}
		},
		/**
		 * 选择支付方式
		 * @param {Object} index
		 */
		selectPayType(index) {
			this.payType = index;
		},
		getBalance() {
			this.sendRequest({
				url: 'System.Pay.maxPayBalance',
				data: { out_trade_no: this.outTradeNo },
				success: res => {
					if (res.code == 0) {
						this.balance = res.data.balance;
						if(this.balance > 0 && this.payInfo.type != 4){
							this.refreshBalance();
						}
					}
				}
			});
		},
		useBalance(e) {
			this.isUseBalance = e.detail.value;
			this.refreshBalance();
		},
		refreshBalance(){
			this.payInfo.pay_money = this.payMoney;
			if (this.isUseBalance) {
				this.payInfo.pay_money -= parseFloat(this.balance);
				if (this.payInfo.pay_money < 0) {
					this.payInfo.pay_money = 0;
				}
			}
			this.payInfo.pay_money = parseFloat(this.payInfo.pay_money).toFixed(2);
		},
		async bindBalance() {
			let res = await this.sendRequest({
				url: 'System.Pay.orderBindBalance',
				async: false,
				data: {
					out_trade_no: this.outTradeNo,
					is_use_balance: 1
				}
			});

			let data = res.data;
			if (data.code == 1) {
				this.$util.redirectTo('/pages/pay/callback_pay/callback_pay', { out_trade_no: this.outTradeNo }, '', 'redirectTo');
				return false;
			} else if (data.code == 0) {
				return true;
			} else if (data.code < 0) {
				this.$util.showToast({ title: data.message });
				return false;
			}
		}
	},
	onShow() {
		var isLogin = false;
		// #ifdef H5
		getApp().checkLogin(() => {
			isLogin = true;
			setTimeout(() => {
				this.$refs.login.clickLogin();
			}, 100);
		});
		// #endif
		// #ifdef MP
		getApp().$vm.checkLogin(() => {
			isLogin = true;
			this.$refs.login.clickLogin();
		});
		// #endif

		if (isLogin) return;

		this.getPayInfo();
		this.getPayType();
		this.getBalance();
	},
	mixins: [http]
};
</script>

<style lang="scss">
page {
	overflow: hidden;
}
@mixin flex-column {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}
@mixin flex-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
}
.payment-amount {
	@include flex-column;
	margin: $ns-margin;
	border-radius: 8rpx;
	padding: 20rpx 0;
	background-color: #fff;
	.amount-tit {
		font-size: $ns-font-size-base;
	}
	.amount-num {
		margin: 10rpx 0;
		text {
			font-size: $ns-font-size-lg + 24rpx;
		}
	}
	.amount-desc {
		font-size: $ns-font-size-base;
		color: $ns-text-color-gray;
		padding: 0 40rpx;
		width: 100%;
		box-sizing: border-box;
		text-align: center;
		text {
			width: 100%;
			display: block;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
	}
}
.payment-balance {
	@include flex-row;
	margin: $ns-margin;
	border-radius: 8rpx;
	padding: 0 30rpx;
	height: 104rpx;
	background-color: #fff;
	font-size: $ns-font-size-lg;
	.balance-num {
		margin-left: 6rpx;
		margin-right: auto;
	}
}
.payment-style {
	margin: $ns-margin;
	border-radius: 8rpx;
	padding: 0 30rpx 20rpx;
	background-color: #fff;
	.style-tit {
		height: 84rpx;
		line-height: 84rpx;
		font-size: $ns-font-size-lg;
		color: $ns-text-color-gray;
	}
	.style {
		@include flex-row;
		height: 104rpx;
		.pic {
			font-size: 50rpx;
		}
		.iconweixinzhifu {
			color: #24af41;
		}
		.iconzhifubaozhifu- {
			color: #00a0e9;
		}
		text {
			margin-left: 20rpx;
			margin-right: auto;
			font-size: $ns-font-size-lg;
		}
	}
}
.payment-btn {
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	margin: 0;
	height: 90rpx;
	line-height: 90rpx;
	font-size: $ns-font-size-base;
	border-radius: 0;
	font-size: $ns-font-size-lg;
}
.payment-bottom {
	bottom: 68rpx !important;
}
</style>
